import PocketBase from 'pocketbase';
import { POCKETBASE_URL, log } from '../config/config.js';

// 创建 PocketBase 实例
const pb = new PocketBase(POCKETBASE_URL);

// 初始化认证状态（从localStorage恢复）
const initAuth = () => {
  // PocketBase 会自动从 localStorage 恢复认证状态
  log('初始化认证状态:', 'debug');
  log(`认证状态: ${pb.authStore.isValid ? '有效' : '无效'}`, 'debug');
  log(`Token: ${pb.authStore.token ? '存在' : '不存在'}`, 'debug');
};

// 在模块加载时初始化
initAuth();

// 获取当前认证状态
export const isAuthenticated = () => {
  return pb.authStore.isValid;
};

// 获取当前认证信息
export const getAuthInfo = () => {
  return {
    isValid: pb.authStore.isValid,
    token: pb.authStore.token,
    model: pb.authStore.model
  };
};

// 管理员登录
export const adminLogin = async (email, password) => {
  try {
    const adminAuth = await pb.send('/api/admins/auth-with-password', {
      method: 'POST',
      body: { identity: email, password },
    });

    
    // 手动设置认证状态到 authStore
    pb.authStore.save(adminAuth.token, adminAuth.admin);
    
    return { success: true, data: adminAuth };
  } catch (error) {
    console.error('管理员登录失败:', error);
    return { success: false, error: error.message };
  }
};

// 退出登录
export const logout = () => {
  pb.authStore.clear();
};

// 获取商品列表，支持分页和筛选
export const getProductList = async (page = 1, perPage = 40, filters = {}) => {
  try {
    let filterString = '';
    
    if (filters.productName) {
      filterString += `product_name ~ "${filters.productName}"`;
    }
    if (filters.status !== undefined) {
      if (filterString) filterString += ' && ';
      filterString += `status = ${filters.status} `;
    }
    if (filters.belongto_store) {
      if (filterString) filterString += ' && ';
      filterString += `belongto_store = "${filters.belongto_store}"`;
    }
    
    const options = {
      sort: '-created',
    };
    
    if (filterString) {
      options.filter = filterString;
    }
    
    const resultList = await pb.collection('points_product').getList(page, perPage, options);
    return { success: true, data: resultList };
  } catch (error) {
    console.error('获取商品列表失败:', error);
    return { success: false, error: error.message };
  }
};

// 获取单个商品
export const getProduct = async (id) => {
  try {
    const record = await pb.collection('points_product').getOne(id);
    return { success: true, data: record };
  } catch (error) {
    console.error('获取商品详情失败:', error);
    return { success: false, error: error.message };
  }
};

// 创建商品
export const createProduct = async (productData) => {
  try {
    const formData = new FormData();
    
    // 添加常规字段
    for (const key in productData) {
      if (key !== 'image_file') {
        formData.append(key, productData[key]);
      }
    }
    
    // 添加图片
    if (productData.image_file) {
      formData.append('image_file', productData.image_file);
    }
    
    const record = await pb.collection('points_product').create(formData);
    return { success: true, data: record };
  } catch (error) {
    console.error('创建商品失败:', error);
    return { success: false, error: error.message };
  }
};

// 更新商品
export const updateProduct = async (id, productData) => {
  try {
    const formData = new FormData();
    
    // 添加常规字段
    for (const key in productData) {
      if (key !== 'image_file') {
        formData.append(key, productData[key]);
      }
    }
    
    // 添加图片，如果有新图片
    if (productData.image_file && productData.image_file instanceof File) {
      formData.append('image_file', productData.image_file);
    }
    
    const record = await pb.collection('points_product').update(id, formData);
    return { success: true, data: record };
  } catch (error) {
    console.error('更新商品失败:', error);
    return { success: false, error: error.message };
  }
};

// 删除商品
export const deleteProduct = async (id) => {
  try {
    await pb.collection('points_product').delete(id);
    return { success: true };
  } catch (error) {
    console.error('删除商品失败:', error);
    return { success: false, error: error.message };
  }
};

// 获取图片URL
export const getImageUrl = (collectionId, id, fileName) => {
  if (!fileName) return '';
  // 使用固定的集合名称 'points_product'
  return `${POCKETBASE_URL}/api/files/points_product/${id}/${fileName}`;
};

// 核销码兑换
export const redeemProductCode = async (code,store_id ) => {
  
  
  try {
    // 检查是否已认证
    if (!pb.authStore.isValid) {
      return { success: false, error: '未登录，请先登录管理员账户' };
    }

    const response = await pb.send('/api/custom/tis/redeem-product-code', {
      method: 'POST',
      body: { code,store_id },
      headers: {
        'Authorization': `Bearer ${pb.authStore.token}`
      }
    });
    return { success: true, data: response };
  } catch (error) {
    console.error('核销码兑换失败:', error);
    return { success: false, error: error.error };
  }
};

// 获取兑换记录列表，支持分页和筛选
export const getExchangeRecords = async (page = 1, perPage = 10, filters = {}) => {
  try {
    let filterString = '';
    
    if (filters.userEmail) {
      filterString += `user_email ~ "${filters.userEmail}"`;
    }
    if (filters.belongto_store) {
      filterString += `${filterString ? ' && ' : ''}belongto_store = "${filters.belongto_store}"`;
    }
    
    const options = {
      sort: '-created',
    };
    
    if (filterString) {
      options.filter = filterString;
    }
    
    const resultList = await pb.collection('exchange_product').getList(page, perPage, options);
    return { success: true, data: resultList };
  } catch (error) {
    console.error('获取兑换记录失败:', error);
    return { success: false, error: error.message };
  }
};

// 通过手机号查询店铺是否存在
export const getStoreByPhone = async (phone) => {
  try {
    const filter = `own_phone='${phone}'`;
    const result = await pb.collection('store').getList(1, 40, { filter });
    console.log('查询店铺结果:', result,result.items.length);
    if (result && result.items && result.items.length > 0) {
      console.log('店铺正确流程');
      return { success: true, data: result};
    } else {
      return { success: false, error: '未找到对应店铺' };
    }
  } catch (error) {
    console.error('查询店铺失败:', error);
    return { success: false, error: error.message };
  }
};

export { pb };